<template>
  <el-dialog
    :title="title"
    :visible.sync="termOpen"
    width="500px"
    append-to-body
    @update:visible="$emit('update:visible', $event)"
  >
    <el-form
      ref="termForm"
      :model="termForm"
      :rules="termRules"
      label-width="120px"
    >
      <el-form-item label="产品" prop="productId">
        <el-select
          v-model="termForm.productId"
          placeholder="请选择产品"
          @change="handleProductChange"
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="deviceId">
        <el-select
          v-model="termForm.deviceId"
          placeholder="请选择设备"
          :disabled="!termForm.productId"
        >
          <el-option
            v-for="item in deviceOptions"
            :key="item.deviceId"
            :label="item.deviceName"
            :value="item.deviceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="属性" prop="attributeId">
        <el-select
          v-model="termForm.attributeId"
          placeholder="请选择属性"
          :disabled="!termForm.productId"
        >
          <el-option
            v-for="item in attributeOptions"
            :key="item.attributeId"
            :label="item.attributeName"
            :value="item.attributeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="比较运算符" prop="comparisonOperator">
        <el-select
          v-model="termForm.comparisonOperator"
          placeholder="请选择对比条件"
        >
          <el-option
            v-for="dict in dict.type.iot_comparison_operator"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="属性值"
        prop="valueMax"
        v-if="
          termForm.comparisonOperator !== 'range' &&
          termForm.comparisonOperator !== 'contain'
        "
      >
        <el-input v-model="termForm.valueMax" placeholder="请输入属性值" />
      </el-form-item>
      <el-form-item
        label="最小值"
        prop="valueMin"
        v-if="termForm.comparisonOperator === 'range'"
      >
        <el-input v-model="termForm.valueMin" placeholder="请输入最小值" />
      </el-form-item>
      <el-form-item
        label="最大值"
        prop="valueMax"
        v-if="termForm.comparisonOperator === 'range'"
      >
        <el-input v-model="termForm.valueMax" placeholder="请输入最大值" />
      </el-form-item>
      <el-form-item
        label="值集合"
        prop="valueList"
        v-if="termForm.comparisonOperator === 'contain'"
      >
        <el-input
          v-model="termForm.valueList"
          type="textarea"
          placeholder="请输入值集合，多个值用逗号分隔"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitTermForm">确 定</el-button>
      <el-button @click="cancelTerm">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addTerm, updateTerm, getTerm } from "@/api/system/iot/term";
import { findProductConfigList } from "@/api/system/iot/product";
import { listDevice } from "@/api/system/iot/device";
import { listAttribute } from "@/api/system/iot/attribute";

export default {
  dicts: ["iot_comparison_operator"],
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    triggerId: {
      type: [String, Number],
      required: true,
    },
    term: {
      type: Object,
      default: () => ({}),
    },
    title: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      termOpen: this.visible,
      termForm: {
        termId: undefined,
        triggerId: this.triggerId,
        productId: undefined,
        deviceId: undefined,
        attributeId: undefined,
        attributeName: undefined,
        comparisonOperator: undefined,
        valueMax: undefined,
        valueMin: undefined,
        valueList: undefined,
      },
      productOptions: [],
      deviceOptions: [],
      attributeOptions: [],
      termRules: {
        productId: [
          { required: true, message: "产品ID不能为空", trigger: "blur" },
        ],
        deviceId: [
          { required: true, message: "设备ID不能为空", trigger: "blur" },
        ],
        attributeId: [
          { required: true, message: "属性ID不能为空", trigger: "blur" },
        ],
        attributeName: [
          { required: true, message: "属性名称不能为空", trigger: "blur" },
        ],
        comparisonOperator: [
          { required: true, message: "对比条件不能为空", trigger: "change" },
        ],
        valueMax: [
          { required: true, message: "属性值不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    visible(newVal) {
      this.termOpen = newVal;
      if (newVal) {
        this.loadProductOptions();
        if (this.term.termId) {
          getTerm(this.term.termId).then((response) => {
            if (response.data.productId) {
              this.handleProductChange(response.data.productId);
            }
            setTimeout(() => {
              this.termForm = response.data;
            }, 100);
          });
        } else {
          this.resetTermForm();
        }
      }
    },
  },
  methods: {
    handleProductChange(productId) {
      this.termForm.deviceId = undefined;
      this.termForm.attributeId = undefined;
      this.termForm.attributeName = undefined;
      this.deviceOptions = [];
      this.attributeOptions = [];
      if (productId) {
        listDevice({ productId: productId }).then((response) => {
          this.deviceOptions = response.rows;
        });
        listAttribute({ productId: productId }).then((response) => {
          this.attributeOptions = response.rows;
        });
      }
    },
    loadProductOptions() {
      findProductConfigList().then((response) => {
        this.productOptions = response.data;
      });
    },
    submitTermForm() {
      this.$refs["termForm"].validate((valid) => {
        if (valid) {
          if (this.termForm.termId) {
            updateTerm(this.termForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.termOpen = false;
              this.$emit("update:visible", false);
              this.$emit("term-updated");
            });
          } else {
            addTerm(this.termForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.termOpen = false;
              this.$emit("update:visible", false);
              this.$emit("term-updated");
            });
          }
        }
      });
    },
    cancelTerm() {
      this.termOpen = false;
      this.$emit("update:visible", false);
      this.resetTermForm();
    },
    resetTermForm() {
      this.termForm = {
        termId: undefined,
        triggerId: this.triggerId,
        productId: undefined,
        deviceId: undefined,
        attributeId: undefined,
        attributeName: undefined,
        comparisonOperator: undefined,
        valueMax: undefined,
        valueMin: undefined,
        valueList: undefined,
      };
      this.$refs["termForm"] && this.$refs["termForm"].resetFields();
    },
  },
};
</script>
